package tree.二叉树的右视图;

import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        /**
         * 层序遍历，取每层的最后一个(队列，先进先出)
         */
        List<Integer> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                root = queue.poll();
                if (root != null) {
                    if(size == 1) {
                        ans.add(root.val);
                    }
                    if (root.left != null){
                        queue.offer(root.left);
                    }
                    if (root.right != null){
                        queue.offer(root.right);
                    }
                }
                size--;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.rightSideView(new TreeNode(1, new TreeNode(2, new TreeNode(4,new TreeNode(5),null), null), new TreeNode(3))));


    }
}
